package com.git.contractmanagement.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);

    // 文件上传目录配置
    @Value("${file.upload-dir}")
    private String uploadDir;

    // 预览图目录配置
    @Value("${file.preview-dir}")
    private String previewDir;

    // 上传文件URL前缀
    @Value("${file.upload-url-prefix:/uploads}")
    private String uploadUrlPrefix;

    // 预览图URL前缀
    @Value("${file.preview-url-prefix:/previews}")
    private String previewUrlPrefix;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置上传文件的资源映射
        configureResourceHandler(registry, uploadUrlPrefix, uploadDir, "上传文件");

        // 配置预览图的资源映射
        configureResourceHandler(registry, previewUrlPrefix, previewDir, "预览图片");

        // 静态资源配置（前端资源）
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/")
                .setCachePeriod(3600);

        // webjars资源配置
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 统一配置资源处理器的方法
     */
    private void configureResourceHandler(ResourceHandlerRegistry registry, String urlPrefix, String dirPath, String resourceType) {
        // 校验目录路径
        if (dirPath == null || dirPath.trim().isEmpty()) {
            throw new IllegalArgumentException(resourceType + "目录配置不能为空");
        }

        // 规范化URL前缀
        String normalizedUrlPrefix = urlPrefix;
        if (!normalizedUrlPrefix.startsWith("/")) {
            normalizedUrlPrefix = "/" + normalizedUrlPrefix;
        }
        if (!normalizedUrlPrefix.endsWith("/")) {
            normalizedUrlPrefix = normalizedUrlPrefix + "/";
        }

        // 规范化文件路径（适配Windows和Linux路径）
        String filePath = dirPath.replace("\\", "/");
        if (!filePath.endsWith("/")) {
            filePath = filePath + "/";
        }

        // 确保使用file:协议前缀
        String fileLocation = "file:" + filePath;

        // 注册资源处理器
        registry.addResourceHandler(normalizedUrlPrefix + "**")
                .addResourceLocations(fileLocation)
                .setCachePeriod(0); // 不缓存上传的文件，确保修改后能立即生效

        logger.info("{}资源映射: {}** -> {}", resourceType, normalizedUrlPrefix, fileLocation);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 根路径映射到index.html，支持SPA应用刷新页面
        registry.addViewController("/").setViewName("forward:/index.html");

        // 为前端路由提供回退处理，确保SPA应用的路由正常工作
        registry.addViewController("/contracts/**").setViewName("forward:/index.html");
        registry.addViewController("/login").setViewName("forward:/index.html");
        registry.addViewController("/dashboard").setViewName("forward:/index.html");

        // favicon处理
        registry.addViewController("/favicon.ico")
                .setStatusCode(HttpStatus.NO_CONTENT);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 配置CORS，允许前端应用访问后端API
        registry.addMapping("/api/**")
                .allowedOrigins(
                        "http://localhost:8080",  // Vue开发服务器
                        "http://localhost:8081",  // Vue开发服务器(另一种端口)
                        "http://127.0.0.1:8080",
                        "http://127.0.0.1:8081"
                )
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("Content-Disposition", "Content-Type", "Content-Length")
                .allowCredentials(true)
                .maxAge(3600);

        // 支付相关接口的跨域配置
        registry.addMapping("/api/pay/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("Content-Disposition", "Content-Type", "Content-Length")
                .maxAge(3600);

        // 允许静态资源的跨域访问
        registry.addMapping("/uploads/**")
                .allowedOrigins("*")
                .allowedMethods("GET")
                .maxAge(3600);

        registry.addMapping("/previews/**")
                .allowedOrigins("*")
                .allowedMethods("GET")
                .maxAge(3600);
    }
}